package com.zhaoyu.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zhaoyu.model.common.dtos.ResponseResult;
import com.zhaoyu.model.common.enums.AppHttpCodeEnum;
import com.zhaoyu.model.user.dtos.LoginDto;
import com.zhaoyu.model.user.pojos.ApUser;
import com.zhaoyu.user.mapper.ApUserMapper;
import com.zhaoyu.user.service.ApUserLoginService;
import com.zhaoyu.utils.common.AppJwtUtil;
import com.zhaoyu.utils.common.BCrypt;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {

    @Autowired
    private ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDto loginDto) {
        // 检查参数
        if (loginDto.getEquipmentId() == null && StringUtils.isEmpty(loginDto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 手机号+密码登录
        if (!StringUtils.isEmpty(loginDto.getPassword())){
            // 用户登录
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, loginDto.getPhone()));
            if (apUser != null){
                // MD5加密
                // if (apUser.getPassword().equals(DigestUtils.md5DigestAsHex((loginDto.getPassword() + apUser.getSalt()).getBytes()))){
                // Bcrypt加密
                if (BCrypt.checkpw(loginDto.getPassword(),apUser.getPassword())){
                    Map<String,Object> map = new HashMap<>();
                    apUser.setPassword("");
                    apUser.setSalt("");
                    map.put("token",AppJwtUtil.getToken(apUser.getId().longValue()));
                    map.put("user",apUser);
                    return ResponseResult.okResult(map);
                }else {
                    return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
                }
            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
            }
        }else {
            // 设备登录
            if (loginDto.getEquipmentId() == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            Map<String,Object> map = new HashMap<>();
            map.put("token",AppJwtUtil.getToken(0l));
            return ResponseResult.okResult(map);
        }
    }

}